package com.leased.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leased.core.ActionContext;
import com.leased.exception.DatabaseException;
import com.leased.exception.YCException;
import com.leased.pojo.CUsers;
import com.leased.pojo.OperateRecordInfo;
import com.leased.pojo.UserLoginLimit;
import com.leased.pojo.ZUsers;
import com.leased.request.cuser.CUserListRequest;
import com.leased.request.operate.OperateRecordRequest;
import com.leased.request.userloginlimit.UserLoginLimitRequest;
import com.leased.request.zuser.ZUserListRequest;
import com.leased.request.zuser.ZUsersAddRequest;
import com.leased.response.*;
import com.leased.service.CUserService;
import com.leased.service.OperateRecordService;
import com.leased.service.UserLoginLimitService;
import com.leased.service.ZUserService;
import com.leased.utils.DateTimeUtil;
import com.leased.utils.Page;
import com.leased.utils.Validator;
import com.leased.utils.YCSystemStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by shencx on 2017/7/28.
 */
@Service
public class ZUserHandler {

    Logger LOG = LoggerFactory.getLogger(ZUserHandler.class);

    @Resource
    private ZUserService zUserService;

    @Resource
    private UserLoginLimitService userLoginLimitService;

    @Resource
    private OperateRecordService operateRecordService;

    @Resource
    private CUserService cUserService;


    /**
     * 添加修改专线用户
     * @param zUsersAddRequest
     * @throws YCException
     */
    public void editZUserInfo(ZUsersAddRequest zUsersAddRequest) throws YCException {
        /** 参数校验 */
        Validator.isEmpty(zUsersAddRequest, YCSystemStatusEnum.PARAM_EMPTY);
        Validator.isEmpty(zUsersAddRequest.getUserName(),"帐号不能为空");
        Validator.isEmpty(zUsersAddRequest.getPassword(),"密码不能为空");
        ZUsers zUsers = new ZUsers();
        zUsers.setId(zUsersAddRequest.getId());
        zUsers.setUserName(zUsersAddRequest.getUserName());
        zUsers.setPassword(zUsersAddRequest.getPassword());
        zUsers.setPhoneNumber(zUsersAddRequest.getPhoneNumber());
        zUsers.setCompanyName(zUsersAddRequest.getCompanyName());
        zUsers.setCompanyAddress(zUsersAddRequest.getCompanyAddress());
        zUsers.setCompanyPhone(zUsersAddRequest.getCompanyPhone());
        zUsers.setCompanyIntroduce(zUsersAddRequest.getCompanyIntroduce());
        zUsers.setRealName(zUsersAddRequest.getRealName());
        zUsers.setOperateName(ActionContext.getActionContext().currentUser().getName());

        zUsers.setStartLine(zUsersAddRequest.getStartAddress());
        zUsers.setDestLine(zUsersAddRequest.getEndAddress());
        zUsers.setBelongProvince(zUsersAddRequest.getBelongProvince());
        zUsers.setBelongCity(zUsersAddRequest.getBelongCity());
        zUsers.setBelongCounty(zUsersAddRequest.getBelongCounty());
        try {
            //没有专线主键ID则添加，否则修改
            if (zUsers.getId() == null){
                Integer id = zUserService.addZUserInfo(zUsers);
                if (id > 0){
                    //添加用户权限信息
                    JSONArray jsonArray = JSON.parseArray(zUsersAddRequest.getExpireTime());
                    for (Object object : jsonArray) {
                        JSONObject jsonObject = JSONObject.parseObject(object.toString());
                        UserLoginLimit userLoginLimit = new UserLoginLimit();
                        userLoginLimit.setUserId(id);
                        userLoginLimit.setUserType(2);
                        userLoginLimit.setPlatformType(Integer.valueOf(jsonObject.get("platformType").toString()));
                        //到期时间有值则开通，没有则没
                        if (StringUtils.isNoneBlank(jsonObject.get("expireTime").toString())){
                            userLoginLimit.setBeUsed(1);
                            userLoginLimit.setExpireTime(DateTimeUtil.convertDate(jsonObject.get("expireTime").toString()));
                        }else {
                            userLoginLimit.setBeUsed(0);
                            userLoginLimit.setExpireTime(new Date());
                        }
                        userLoginLimitService.addUserLoginLimitInfo(userLoginLimit);
                    }
                }
            }else {
                boolean flag = zUserService.updateZUserInfo(zUsers);
                //更新成功 插入操作记录
                if (flag){
                    OperateRecordInfo operateRecordInfo = new OperateRecordInfo();
                    operateRecordInfo.setUserType(2);
                    operateRecordInfo.setUserAccount(zUsersAddRequest.getUserName());
                    operateRecordInfo.setOperateName(ActionContext.getActionContext().currentUser().getName());
                    operateRecordInfo.setOperateDescribe("修改了"+zUsersAddRequest.getUserName()+"信息");
                    operateRecordService.addOperateRecordInfo(operateRecordInfo);
                }
            }
        }catch (DatabaseException e) {
            LOG.error("editZUserInfo exception",zUsers);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 获取专线用户信息列表
     * @param zUserListRequest
     * @return
     * @throws YCException
     */
    public Page<ZUserResponse> getZUserInfoPage(ZUserListRequest zUserListRequest) throws YCException {
        Page<ZUserResponse> page = null;
        //默认查询昨天和今天的用户 ,只要查询条件有不为空的，都不设置成默认查询
        if (StringUtils.isNoneBlank(zUserListRequest.getUserName()) || StringUtils.isNoneBlank(zUserListRequest.getRealName()) || StringUtils.isNoneBlank(zUserListRequest.getPhoneNumber())
                || StringUtils.isNoneBlank(zUserListRequest.getStartTime()) || StringUtils.isNoneBlank(zUserListRequest.getEndTime())){

        }else {
            zUserListRequest.setStartTime(DateTimeUtil.formatDate(getNextDay(-1)));
            zUserListRequest.setEndTime(DateTimeUtil.formatDate(getNextDay(0)));
        }
        try {
            page = zUserService.fetchZUserInfoPage(zUserListRequest);
            return page;
        } catch (DatabaseException e) {
            LOG.error("getZUserInfoPage exception",zUserListRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 获取专线用户详情
     * @param zUserListRequest
     * @return
     * @throws YCException
     */
    public ZUsers getZUserDetail(ZUserListRequest zUserListRequest) throws YCException {
        ZUsers zUsers = null;
        try {
            zUsers = zUserService.fetchZUserDetail(zUserListRequest);
            return zUsers;
        } catch (DatabaseException e) {
            LOG.error("getZUserDetail exception",zUserListRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 根据主键获取专线详情
     * @param id
     * @return
     * @throws YCException
     */
    public ZUserDetailResponse getZUserDetailById(Integer id) throws YCException {
        /** 参数校验 */
        Validator.isEmpty(id,"主键ID不能为空");
        ZUserListRequest zUserListRequest = new ZUserListRequest();
        zUserListRequest.setId(id);
        try {
            ZUsers zUsers = zUserService.fetchZUserDetail(zUserListRequest);
            ZUserDetailResponse zUserDetailResponse = new ZUserDetailResponse();
            if (zUsers != null){
                zUserDetailResponse.setUserName(zUsers.getUserName());
                zUserDetailResponse.setPassword(zUsers.getPassword());
                zUserDetailResponse.setPhoneNumber(zUsers.getPhoneNumber());
                zUserDetailResponse.setRealName(zUsers.getRealName());
                zUserDetailResponse.setRegisterTime(zUsers.getRegisterTime());
                zUserDetailResponse.setCompanyName(zUsers.getCompanyName());
                zUserDetailResponse.setCompanyAddress(zUsers.getCompanyAddress());
                zUserDetailResponse.setCompanyIntroduce(zUsers.getCompanyIntroduce());
                zUserDetailResponse.setCompanyPhone(zUsers.getCompanyPhone());
                zUserDetailResponse.setWallet(zUsers.getWallet());

                zUserDetailResponse.setStartLine(zUsers.getStartLine());
                zUserDetailResponse.setDestLine(zUsers.getDestLine());
                zUserDetailResponse.setBelongProvince(zUsers.getBelongProvince());
                zUserDetailResponse.setBelongCity(zUsers.getBelongCity());
                zUserDetailResponse.setBelongCounty(zUsers.getBelongCounty());

                //获取权限记录
                List<UserLoginLimit> list = userLoginLimitService.fetchUserLoginLimitList(id,2);
                zUserDetailResponse.setLimitList(list);
                //获取操作记录
                OperateRecordRequest request = new OperateRecordRequest();
                request.setUserType(2);
                request.setUserAccount(zUsers.getUserName());
                List<OperateRecordInfo> recordInfoList = operateRecordService.fetchOperateRecordList(request);
                zUserDetailResponse.setOperateRecordInfoList(recordInfoList);
            }
            return zUserDetailResponse;
        }catch (DatabaseException e) {
            LOG.error("getZUserDetailById exception",id);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }


    public static Date getNextDay(Integer value) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, value);
        date = calendar.getTime();
        return date;
    }

    /**
     * 根据手机号查询
     * @param phoneNumber
     * @return
     */
    public PhoneNumberResponse getUserByPhoneNumber(String phoneNumber) throws YCException {
        PhoneNumberResponse phoneNumberResponse = new PhoneNumberResponse();
        ZUserListRequest zUserListRequest = new ZUserListRequest();
        zUserListRequest.setPhoneNumber(phoneNumber);
        CUserListRequest cUserListRequest = new CUserListRequest();
        cUserListRequest.setPhoneNumber(phoneNumber);
        try {
            if (StringUtils.isNoneBlank(phoneNumber)){
                ZUsers zUsers = zUserService.fetchZUserDetail(zUserListRequest);
                if (zUsers != null ) {
                    ZUserResponse zUserResponse = new ZUserResponse();
                    zUserResponse.setId(zUsers.getId());
                    zUserResponse.setUserName(zUsers.getUserName());
                    zUserResponse.setRealName(zUsers.getRealName());
                    zUserResponse.setPhoneNumber(zUsers.getPhoneNumber());
                    zUserResponse.setOperateName(zUsers.getOperateName());
                    zUserResponse.setRegisterTime(zUsers.getRegisterTime());
                    zUserResponse.setUserType("专线");
                    phoneNumberResponse.setzUserResponse(zUserResponse);
                }
                CUsers cUsers = cUserService.fetchCUserDetail(cUserListRequest);
                if (cUsers != null) {
                    CUserResponse cUserResponse = new CUserResponse();
                    cUserResponse.setId(cUsers.getCuserId());
                    cUserResponse.setUserName(cUsers.getUsername());
                    cUserResponse.setRealName(cUsers.getCertName());
                    cUserResponse.setPhoneNumber(cUsers.getPhone());
                    cUserResponse.setOperateName(cUsers.getOperateName());
                    cUserResponse.setRegisterTime(cUsers.getRegisterTime());
                    cUserResponse.setUserType("车主");
                    phoneNumberResponse.setcUserResponse(cUserResponse);
                }
            }else {
                phoneNumberResponse.setcUserResponse(null);
                phoneNumberResponse.setzUserResponse(null);
            }
            return phoneNumberResponse;
        } catch (DatabaseException e) {
            LOG.error("getUserByPhoneNumber exception", phoneNumber);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 获取用户数
     * @return
     * @throws YCException
     */
    public UserCountResponse getUserCount() throws YCException {
        UserCountResponse userCountResponse = null;
        try {
            userCountResponse = zUserService.fetchCountNum();
            return userCountResponse;
        }  catch (DatabaseException e) {
            LOG.error("getUserCount exception");
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

}
